﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GabageFactory.Models;

namespace GabageFactory.Controllers
{
    [Authorize]
    public class ModificationController : BaseController
    {
        private ModificationReposity modificationReposity;

        private UserReposity userReposity;


        public ModificationController()
        {
            modificationReposity = new ModificationReposity();
            userReposity = new UserReposity();
        }

        //
        // GET: /Factory/

        public ActionResult OwnedIndex()
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            return View(modificationReposity.ListOwnedApplies(GetCurrentUser().Id));
        }

        public ActionResult FactoryIndex()
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Auditor);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            return View(modificationReposity.ListFactoryApplies(GetCurrentUser().FactoryId));
        }

        public ActionResult Index()
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            return View(modificationReposity.ListApplies());
        }

        //
        // GET: /Factory/Details/5

        public ActionResult Detail(int id)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Administrator);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            Apply apply = modificationReposity.GetDetailById(id);
            ViewData["role"] = (RoleEnum)GetCurrentUser().RoleId;
            return View(apply);
        }

        //
        // GET: /Modification/Create

        public ActionResult Create()
        {
            ActionResult result = AllowForRole(RoleEnum.Recorder);
            if (result != null)
            {
                return result;
            }
            return View(new Modification_apply());
        }

        //
        // POST: /Factory/Create

        [HttpPost]
        public ActionResult Create(Modification_apply apply, HttpPostedFileWrapper file)
        {
            ActionResult result = AllowForRole(RoleEnum.Recorder);
            if (result != null)
            {
                return result;
            }
            try
            {
                validate(apply);
                apply.applier = GetCurrentUser().Id;
                if (file != null)
                {
                    string fileName = UploadFile(file, FileType.Doc);

                    apply.file = fileName;
                }
                
                apply = modificationReposity.CreateApply(apply);

                return RedirectToAction("OwnedIndex");
            }
            catch
            {
                return View(apply);
            }
        }

        //
        // GET: /Factory/Edit/5

        public ActionResult Edit(int id)
        {
            ActionResult result = AllowForRole(RoleEnum.Recorder);
            if (result != null)
            {
                return result;
            }
            Modification_apply apply = modificationReposity.GetApplyById(id);
            ViewData["id"] = id;
            return View(apply);
        }

        //
        // POST: /Factory/Edit/5

        [HttpPost]
        public ActionResult Edit(Modification_apply apply, HttpPostedFileWrapper file)
        {
            ActionResult result = AllowForRole(RoleEnum.Recorder);
            if (result != null)
            {
                return result;
            }
            try
            {
                ViewData["id"] = apply.id;
                validate(apply);
                apply.applier = GetCurrentUser().Id;
                if (file != null)
                {
                    string fileName = UploadFile(file, FileType.Doc);

                    apply.file = fileName;
                }

                Modification_apply oldApply = modificationReposity.GetApplyById(apply.id);
                oldApply.title = apply.title;
                oldApply.content = apply.content;
                oldApply.file = apply.file;
                modificationReposity.EditApply(oldApply);

                return RedirectToAction("OwnedIndex");
            }
            catch
            {
                return View(apply);
            }
        }

        //
        // GET: /Factory/Delete/5

        public ActionResult Delete(int id)
        {
            ActionResult result = AllowForRole(RoleEnum.Recorder);
            if (result != null)
            {
                return result;
            }
            Modification_apply apply = modificationReposity.GetApplyById(id);
            ViewData["title"] = apply.title;

            modificationReposity.DeleteApply(apply);
            return RedirectToAction("OwnedIndex");
        }

        public ActionResult Process(int id, string Action, string Reason)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Administrator);
            roles.Add(RoleEnum.Recorder);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            Modification_apply apply = modificationReposity.GetApplyById(id);
            apply.status = Action == "reject" ? -1 : (Action == "approve" ? 1 : (Action == "finish" ? 2 : 0));
            apply.reason = Reason;
            modificationReposity.EditApply(apply);

            if (GetCurrentUser().RoleId == (int)RoleEnum.Administrator)
            {
                return RedirectToAction("Index");
            }
            else if (GetCurrentUser().RoleId == (int)RoleEnum.Auditor)
            {
                return RedirectToAction("FactoryIndex");
            }

            return RedirectToAction("Detail", new { id });
        }

        public ActionResult SelectFactory()
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Administrator);
            roles.Add(RoleEnum.Recorder);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            ShowFactoryList(0);

            return View();
        }

        public ActionResult ListStacks(int factoryId, int showType = 0)
        {
            ShowStackAndTailingoind(factoryId, showType);
            return View();
        }

        public ActionResult EditData(int FactoryId, string stackId, DateTime date)
        {
            try {
                string[] values = stackId.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                if (values[0] == "0")
                {
                    return RedirectToAction("StackWater", "Record", new { id = values[1], date = date, factoryId = FactoryId });
                }
                else if (values[0] == "1")
                {
                    return RedirectToAction("TailingpondWater", "Record", new { id = values[1], date = date, factoryId = FactoryId });
                }
            }
            catch {
                return RedirectToAction("SelectFactory");
            }
            return RedirectToAction("SelectFactory");
        }

        private void validate(Modification_apply apply)
        {
            if (string.IsNullOrEmpty(apply.title))
            {
                ModelState.AddModelError("title", "标题不能为空");
            }
            else if (apply.title.Length > 128)
            {
                ModelState.AddModelError("title", "标题不能超过128个字符");
            }

            if (string.IsNullOrEmpty(apply.content))
            {
                ModelState.AddModelError("content", "申请内容不能为空");
            }
            else if (apply.content.Length > 500)
            {
                ModelState.AddModelError("content", "申请内容不能超过500个字符");
            }

            if (apply.type <= 0)
            {
                ModelState.AddModelError("type", "申请类型不能为空");
            }

            if (apply.type == 2 && string.IsNullOrEmpty(apply.file))
            {
                ModelState.AddModelError("file", "补录数据文件不能为空");
            }

            if (!ModelState.IsValid)
            {
                throw new Exception("Input form is invalid!");
            }
        }
    }
}
